<?php
/**
 * User: 高振
 * Date: 14-4-4
 * Time: 下午4:12
 * Description：
 */
namespace Common\Org\Upload;
class Del
{

    public function __contruct(){}

    /**
     * @param $doType
     * @param $uid
     * @param $filePathArr
     * @param $callback
     * @param $operator
     * 删除文件
     */
    public function delete($updo,$uid,$filePathArr){
        $do = base64_decode($updo);
        $darr = get_attach($do, $uid);

        $path = IMG_STORE_PATH.rtrim($darr['dir_path']).'/';

        foreach($filePathArr as $savename){
            //$savename = iconv('GB2312','UTF-8',$savename);
            if(IS_WIN){
                $savename = iconv('UTF-8','GB2312',$savename);
            }
            $filePath = $path.$savename;

            if (file_exists($filePath))
            {
                if (unlink($filePath))
                {
                    $mid_file = $path.'/mid_'.$savename;
                    $small_file = $path.'/small_'.$savename;
                    $big_file = $path.'/big_'.$savename;
                    $ios_file = $path.'/ios_'.$savename;
                    if(file_exists($mid_file))  unlink($mid_file);
                    if(file_exists($small_file))  unlink($small_file);
                    if(file_exists($big_file))  unlink($big_file);
                    if(file_exists($ios_file))  unlink($ios_file);
                } else {
                    return array('info'=>'删除失败','status'=>0);
                }
            } else {
                return array('info'=>'删除失败','status'=>0);
            }

        }
        return array('info'=>'删除成功','status'=>1);
    }

    /*
     * 删除文件
     */
    public function _delete($doType,$uid,$filePathArr,$callback,$operator)
    {
        foreach($filePathArr as $filePath)
        {

            $filePath = str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']) . $filePath;
            $filePath = iconv('UTF-8','GB2312',$filePath);
            if (file_exists($filePath))
            {
                if (unlink($filePath))
                {
                        $filename = getFileName($filePath);
                        $dir = dirname($filePath);
                        $mid_file = $dir.'/mid_'.$filename;
                        $small_file = $dir.'/small_'.$filename;
                        $big_file = $dir.'/big_'.$filename;
                        $ios_file = $dir.'/ios_'.$filename;
                        if(file_exists($mid_file))  unlink($mid_file);
                        if(file_exists($small_file))  unlink($small_file);
                        if(file_exists($big_file))  unlink($big_file);
                        if(file_exists($ios_file))  unlink($ios_file);
                }
            }
        }
        return array('msg'=>'sucess','code'=>0);
    }

    /**
     * @param $uid
     * @param $filePath
     * @return int
     */
    public function verify_permission($uid,$filePath)
    {
        $reg = '#MySpace\/(\d+)#';
        preg_match($reg,$filePath,$arr);
        if($uid==$arr[1])
        {
            return 1;
        }
    }

    /**
     * 清理无用文件
     * @param $key
     * @param bool $uid
     * @return array
     */
    public function delInvalidFile($key,$uid=false){
        if(empty($key)) return array('info'=>'param error','status'=>0);

        //获取Memcache中已存在的key
        $fileInMemcached = cache($key);
//        if(!$fileInMemcached){
//            return array('info'=>'invalid error','status'=>0);
//        }

        //遍历目录获取所有文件
        $localeFile = $this->getLocaleFile($uid);
        if(empty($localeFile)){
            return array('info'=>'no invalid file','status'=>2);
        }

        //获取要删除的无效文件
        $delFiles =array_diff($localeFile,$fileInMemcached);
        if(empty($delFiles)){
            return array('info'=>'no invalid file','status'=>2);
        }

        foreach($delFiles as $file){
            @unlink($file);//删除本文件
            $path = substr($file,0,strrpos($file,'/')+1);
            $filename = substr($file,strrpos($file,'/')+1);
            //删除缩略图
            @unlink($path.'big_'.$filename);
            @unlink($path.'mid_'.$filename);
            @unlink($path.'small_'.$filename);
            @unlink($path.'ios_'.$filename);
        }
        cache($key,null);//清除Memcache缓存

        return array('info'=>'success','status'=>1);
    }

    /**
     * 图片库获取数据
     * @param $alias
     * @param bool $uid
     * @param bool $bool
     * @return array
     */
    public function getFileLibrary($alias,$uid=false){
        if(empty($alias)){
            return false;
//            return array('status'=>0,'info'=>'invalid operator');
        }

        $attach = get_attach($alias,$uid);
        $ext_arr =  explode(',',$attach['extension']);

        if(empty($uid)){
            $reg = '/\/(Data\/Admin\/.*\/)/';
        } else {
            $reg = '/\/(Data.*)[0-9]+\//';
        }
        $match[1] = IMG_STORE_PATH.$attach['dir_path'];
        //preg_match($reg,$attach['dir_path'],$match);
        //if(empty($match)){
          //  return false;
//            return array('status'=>0,'info'=>'invalid operator');
        //}
        $files = array();
        $this->getAllFiles($match[1],$files);

        $returnFiles = array();
        foreach($files as $key=>$file){
            $returnFiles[$key]['is_dir'] = false;
            $returnFiles[$key]['has_file'] = false;
            $returnFiles[$key]['filesize'] = filesize($file);
            $returnFiles[$key]['dir_path'] = '';
            $filename = substr($file,strrpos($file,DIRECTORY_SEPARATOR)+1);
            if(IS_WIN){
                $filename = iconv('GB2312','UTF-8',$filename);
            }
            $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            $returnFiles[$key]['is_photo'] = in_array($file_ext, $ext_arr);
            $returnFiles[$key]['filetype'] = $file_ext;
            $returnFiles[$key]['filename'] = $filename;
            if(strtolower($alias)=='content'){
                $returnFiles[$key]['show_filename'] = 'mid_'.$filename;
            } else {
                $returnFiles[$key]['show_filename'] = $filename;
            }

            $returnFiles[$key]['datetime'] = filemtime($file);
            $returnFiles[$key]['full_name'] = $attach['img_root'].$filename;
        }
        return $returnFiles;

//        return array('status'=>1,'library'=>$files);
    }

    public function sortFileLibrary(&$files,$sort){
        //名字，大小，类型（扩展名）
        $name = array();
        $size = array();
        $type = array();
        foreach($files as $key=>$val){
            $name[$key] = $val['filename'];
            $size[$key] = $val['filesize'];
            $type[$key] = $val['filesize'];
        }
        switch($sort){
            case 'name':
                $order = $name;
                break;

            case 'size':
                $order = $size;
                break;

            case 'type':
                $order = $type;
                break;
        }
        array_multisort($order, SORT_ASC, $files);
    }

    /**
     * 获取用户或系统后台所有的文件
     * @param $uid
     * @return array
     */
    private function getLocaleFile($uid,$all=false){
        $files = array();
        if(empty($uid)){
            $this->getAllFiles('./Data/Admin',$files);
        } else if($all){
            $this->getAllFiles('./Data/',$files);
        } else {
            $this->getAllFiles('./Data/MySpace/'.$uid.'/',$files);
        }
        return $files;
    }

    private function getAllFiles($dir,&$files=array()){
        if(!is_dir($dir)){
            return false;
        }
        $d=dir($dir);
        while(FALSE !== ($item = $d->read() )){
            if(IS_WIN){
                $files1 = iconv('GB2312','UTF-8',$item);
            } else {
                $files1 = $item;
            }

            if('.' ==$files1 || '..'==$files1){
                continue;
            }

            //文件存在，且文件不能为缩略图
            if(IS_WIN){
                $newFile = iconv('UTF-8','GB2312',$files1);//中文进行编码
            } else {
                $newFile = $files1;
            }

            if(file_exists('./'.$dir . '/' .$newFile) && strpos($newFile,'_')===false){
                $files[] = realpath($dir . '/' .$newFile);
            } elseif(is_dir($dir . '/' .$newFile) && $files1!='.svn'){
                $this->getAllFiles($dir . '/' .$newFile,$files);
            }
        }
    }
}